// https://nodejs.org/dist/latest-v18.x/docs/api/
var fs = require("fs");
var { existsSync } = require("fs");
var path = require("path");
var utils = require("./utils");
const opn = require("opn");
const prettier = require("prettier");
const copyUtil = require("./copyUtil.js");

const indexFile = "index.tsx";
const configFile = "config.tsx";
const formIndexFile = "\\subComps\\ProFormDynamic\\index.tsx";
const formConfigFile = "\\subComps\\ProFormDynamic\\config.tsx";
const tags = ["///开始", "///结束"];
const deletePattern = [`${tags[0]}删除[\\d\\D]*?${tags[1]}删除`, ".*console.debug.*[\\d\\D]", ".*console.log.*[\\d\\D]", ".*// eslint.*[\\d\\D]"]; // 删除内容 非贪婪匹配
const tagsQuo = ['"///去除引号', '///去除引号"', "'///去除引号", "\\'///去除引号", "///去除引号\\'", '\\"///去除引号', '///去除引号\\"', "///去除引号"];

// 全部文件
type FilesContent = {
  index: string; // 表格index
  config: string; // 表格config
  formIndex: string; // 表单index
  formConfig: string; // 表单config
};

exports.generateProTable = function (res: any, generateData: any) {
  const { name, templatePath, generatePath, tableInfo, formInfo } = generateData;

  const indexFilePath = path.join(templatePath, indexFile); // 文件绝对路径
  const configFilePath = path.join(templatePath, configFile); // 文件绝对路径
  const generateIndexFilePath = path.join(generatePath, indexFile); // 文件绝对路径
  const generateConfigFilePath = path.join(generatePath, configFile); // 文件绝对路径
  const generateFormIndexFilePath = path.join(generatePath, formIndexFile); // 文件绝对路径
  const generateFormConfigFilePath = path.join(generatePath, formConfigFile); // 文件绝对路径
  if (!existsSync(templatePath)) return utils.ResultFail(res, `模板templatePath:${templatePath}路径不存在！`);
  if (!existsSync(indexFilePath)) return utils.ResultFail(res, `模板indexFilePath:${indexFile}不存在！`);
  if (!existsSync(configFilePath)) return utils.ResultFail(res, `模板configFilePath:${configFilePath}不存在！`);

  // 如果目录不存在则创建目录
  if (!existsSync(generatePath)) {
    fs.mkdirSync(generatePath);
  }

  // fs.accessSync(generatePath, fs.constants.R_OK);
  // fs.accessSync(templatePath, fs.constants.R_OK);

  // 复制模板文件夹
  copyUtil.copySync(templatePath, generatePath);
  let filesContent: FilesContent = {
    index: fs.readFileSync(generateIndexFilePath, "utf-8"),
    config: fs.readFileSync(generateConfigFilePath, "utf-8"),
    formIndex: fs.readFileSync(generateFormIndexFilePath, "utf-8"),
    formConfig: fs.readFileSync(generateFormConfigFilePath, "utf-8")
  };
  console.debug("formConfig:", filesContent);

  // 修改ProTable特殊相关内容
  const tableConfigPattern = `${tags[0]}tableInfo[\\d\\D]*${tags[1]}tableInfo`;
  const tableConfigRegExp = new RegExp(tableConfigPattern, "g");
  filesContent.config = filesContent.config.replace(tableConfigRegExp, "return " + tableInfo + ""); // 替换tableInfo

  // 修改ProForm特殊相关内容
  const formConfigPattern = `${tags[0]}formInfo[\\d\\D]*${tags[1]}formInfo`;
  const formConfigRegExp = new RegExp(formConfigPattern, "g");
  filesContent.formConfig = filesContent.formConfig.replace(formConfigRegExp, "return " + formInfo + ""); // 替换formInfo

  // 删除无用代码片段
  filesContent = batchDealStringByRegExp(deletePattern, filesContent, "");
  // 删除引号
  filesContent = batchDealStringByRegExp(tagsQuo, filesContent, "");
  // 美化代码
  const [generateIndexFilePrettierStr, generateIndexFilePrettierSuccess] = prettierFile(filesContent.index);
  const [generateConfigFilePrettierStr, generateConfigFilePrettierSuccess] = prettierFile(filesContent.config);
  const [generateFormIndexFilePrettierStr, generateFormIndexFilePrettierSuccess] = prettierFile(filesContent.formIndex);
  const [generateFormConfigFilePrettierStr, generateFormConfigFilePrettierSuccess] = prettierFile(filesContent.formConfig);
  // 重新写入
  fs.writeFileSync(generateIndexFilePath, generateIndexFilePrettierStr, (error: any) => {
    if (error) console.error(`${path}创建失败：${error}`);
  });
  fs.writeFileSync(generateConfigFilePath, generateConfigFilePrettierStr, (error: any) => {
    if (error) console.error(`${path}创建失败：${error}`);
  });
  fs.writeFileSync(generateFormIndexFilePath, generateFormIndexFilePrettierStr, (error: any) => {
    if (error) console.error(`${path}创建失败：${error}`);
  });
  fs.writeFileSync(generateFormConfigFilePath, generateFormConfigFilePrettierStr, (error: any) => {
    if (error) console.error(`${path}创建失败：${error}`);
  });

  return utils.ResultSuccess(res);
};

// 批量处理字符串
const batchDealStringByRegExp = (regExp: string[], filesContent: FilesContent, replaceStr: string): FilesContent => {
  filesContent.index = replaceStringByRegExpArr(regExp, filesContent.index, replaceStr);
  filesContent.config = replaceStringByRegExpArr(regExp, filesContent.config, replaceStr);
  filesContent.formIndex = replaceStringByRegExpArr(regExp, filesContent.formIndex, replaceStr);
  filesContent.formConfig = replaceStringByRegExpArr(regExp, filesContent.formConfig, replaceStr);
  return filesContent;
};

/** 替换字符串中的标签
 * @param regExpArr 正则数组
 * @param str 要替换的字符串
 * @param replaceStr 要替换成的字符串
 */
const replaceStringByRegExpArr = (regExpArr: string[], str: string, replaceStr: string): string => {
  // console.debug("替换字符串", regExpArr, str, replaceStr);
  for (const i in regExpArr) {
    const regExp = regExpArr[i];
    const pattern = `${regExp}`;
    const runRegExp = new RegExp(pattern, "g");
    str = str.replace(runRegExp, replaceStr);
  }
  return str;
};

// 默认的prettier配置
const defaultPrettierOptions1 = {
  singleQuote: true,
  trailingComma: "all",
  printWidth: 120,
  tabWidth: 2,
  proseWrap: "always",
  endOfLine: "lf",
  bracketSpacing: false,
  arrowFunctionParentheses: "avoid",
  overrides: [
    {
      files: ".prettierrc",
      options: {
        parser: "json"
      }
    },
    {
      files: "document.ejs",
      options: {
        parser: "html"
      }
    }
  ]
};
// Admin项目配置
const defaultPrettierOptions = {
  singleQuote: true,
  trailingComma: "all",
  printWidth: 180,
  overrides: [
    {
      files: ".prettierrc",
      options: { parser: "json" }
    }
  ]
};

// 格式化美化文件
type prettierFileType = (content: string) => [string, boolean];
export const prettierFile: prettierFileType = (content: string) => {
  let result = content;
  let hasError = false;
  try {
    result = prettier.format(content, {
      parser: "typescript",
      ...defaultPrettierOptions
    });
  } catch (error) {
    hasError = true;
  }
  return [result, hasError];
};
